<template>
  <div class="mt-select-wrap mt-picker-wrap mt-picker--{{disabled ? 'disabled' : 'inited'}} mt-picker-column--{{activeSwiperIndex}}">
    <div
      class="mt-picker-trigger"
      @tap="onTrigger"
    >
      <block wx:if="{{!inner_value || inner_value.length < 1 || inner_value[0] < 0 || !labeltext}}">
        <div class="mt-picker__init"><slot name="initial"></slot></div>
      </block>
      <block wx:else>
        <div class="mt-picker__content">
          <block wx:if="{{useSlot}}"><slot></slot></block>
          <block wx:else>{{labeltext}}</block>
        </div>
      </block>
      <div class="mt-picker__action"></div>
    </div>

    <van-popup
      show="{{ showPopup }}"
      position="bottom"
      overlay="{{ true }}"
      @click-overlay="onClickOverlay"
    >

      <div class="ui-flex ui-items-center ui-justify-between mt-picker__control">
        <div class="mt-picker__btn mt-picker__cancel" @tap="onCancel">取消</div>
        <div class="mt-picker__btn mt-picker__confirm" @tap="onConfirm">确定</div>
      </div>
      <div v-for="(inner_item, index) in tmp_values" :key="index">
        <div @tap="setActive" data-index="{{index + 1}}">{{inner_item.label}}</div>
      </div>
      <van-picker
          id="picker"
          columns="{{ inner_columns }}"
          value-key="label"
          @change="onChangeV2"></van-picker>
    </van-popup>
  </div>
</template>

<script>
  const formEmitterBehavior = require('../../behaviors/emitter.behavior')
  const formELementBehavior = require('../../behaviors/form-element.behavior')

  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }

  function guid() {
    return "ss-s-s-s-sss".replace(/s/g, s4);
  }

  function isEmpty(value) {
    return !value || value.length < 1 || value[0] < 0
  }

  function transform(val, level) {
    let r = []
    val.forEach(function (item, index) {
      if (!r[level]) {
        r[level] = {
          values: []
        }
      }
      r[level].values.push({
        label: item.label,
        value: item.value
      })
    })
    return r
  }

  export default {
    behaviors: [
      formEmitterBehavior,
      formELementBehavior
    ],
    relations: {
      '../mt-form-item/index': {
        type: 'ancestor', // 关联的目标节点应为祖先节点
        linked(v) {
          this.formItem = v
          // console.log('this.formItem', this.formItem)
        },
        unlinked() {
          this.formItem = null
        }
      }
    },
    observers: {
      'sModel': function (field) {
        console.log('field', field, this.data.sModel)
        this.setNativeValue()
      }
    },
    properties: {
      sModel: null,
      childrenKey: {
        type: Array,
        value: []
      },
      indicatorStyle: {
        type: String,
        value: 'height: 50px;'
      },
      pickerStyle: {
        type: String,
        value: 'width: 100%; height: 200px;'
      },
      useSlot: {
        type: Boolean,
        value: false,
      },
      disabled: {
        type: Boolean,
        value: false,
      },
      col: {
        type: Number,
        value: 2
      },
      columns: {
        type: null,
        value: null,
        observer(newVal) {
          this.setColumns(this.data.sModel, {}, {
          })
        }
      },
      value: {
        type: null,
        value: null,
        observer(newVal) {
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          if (newValIsNull) {

          } else {
            if (this.data.columns && this.data.columns.length > 1) {
              let picker = this.selectComponent('#picker')
              if (picker) {
                let columns = []
                for (let i = 0; i < this.data.col; i++) {
                  picker.setColumnIndex(i,newVal[i])
                  columns.push(picker.getColumnValue(i))
                }
                console.log('multipicker', newVal, columns)
                this.setData({
                  tmp_model: columns.map(v => v.value)
                })
                wx.nextTick(() => {
                  this.setData({
                    inner_value: newVal,
                  })
                })
              }
            }
          }
        }
      }
    },
    data() {
      return {
        inner_columns: [],
        inner_value: [],
        tmp_model: [],
        showPopup: false,
        labeltext: '',
        columnLen: 0,
        firstLoad: false,
        activeSwiperIndex: 1,
        tmp_values: []
      }
    },
    methods: {
      setActive(e) {
        this.setData({
          activeSwiperIndex: e.target.dataset.index
        })
      },
      setNativeValue() {
        let f = this.data.firstLoad
        let columns = this.data.columns
        console.log('setNativeValue', columns, this.data.sModel,)
        this.setColumns(this.data.sModel, {
          tmp_model: this.data.sModel,
          firstLoad: true,
          autoLabel: true
        }, {
          isFromWatch: true,
          doSet: f
        })
      },
      setColumns(model, obj, options = {}) {
        let self = this
        let op = Object.assign({
          autoLabel: true,
          isFromWatch: false,
          doSet: true
        }, options)

        let columns = this.data.columns
        // console.log('nativeValue', model, columns)

        if (Array.isArray(columns) && columns.length > 0 ) {
          if (Array.isArray(model)) {
            // 数据 选项都有
            let v = this.buildOptions(columns, model, 0)

            console.log('multipicker', v)

            if (op.autoLabel) {
              let inner_value = []
              v.labeltext = this.getLabel(v.inner_columns, v.inner_value)
              // this.getInnerValue(this.data.columns, this.data.tmp_model, inner_value)
              // console.log(' v.labeltext ',  v.labeltext, self.data.inner_value )
              // self.renderLabel(() => {
              //   console.log(' v.labeltext ',  self.data.labeltext, self.data.inner_value )
              // })
            }

            // console.log('isFromWatch', v, op)

            // if (op.doSet) {
            //   if (op.isFromWatch) {
            //     self.callComponent(this.formItem, 'mtFormChange',  [
            //       self.getFormValueFromInnerColumns(v.inner_columns)
            //     ])
            //   }
            //   this.setData(Object.assign(obj, v), () => {
            //     options.onEnd && options.onEnd(v)
            //   })
            // } else {

            // }
              this.setData(Object.assign(obj, {
                inner_columns: v.inner_columns,
                tmp_model:  self.getFormValueFromInnerColumns(v.inner_columns)
              }), () => {
                let picker = this.selectComponent('#picker')
                let values = picker.getValues()
                console.log('sdsdsdsds', picker, values)
                this.setData({
                  tmp_values: values
                })
              })
          }
        }
      },
      getFormValueFromInnerColumns(inner_columns) {
        let arr = []
        for (let i = 0; i < this.data.col; i++) {
          let v = inner_columns[i]
          arr.push(v.values[v.defaultIndex].value)
        }
        return arr
      },
      getInnerValue(columns, model, inner_value, level = 0) {
        let self = this
        let selectedIndex = 0

        columns.forEach( (level1Item, level1Index) => {
          if (level1Item.value === model[level]) {
            selectedIndex = level1Index
          }
        })

        inner_value[level] = selectedIndex
        if (columns[selectedIndex].children) {
          self.getInnerValue(columns[selectedIndex].children, model, inner_value, level + 1)
        }
      },
      buildOptions(columns, model, level) {
        let self = this
        let inner_value = []
        let inner_columns = []
        let selectedIndex = 0
        columns.forEach( (level1Item, level1Index) => {
          if (!inner_columns[level]) {
            inner_columns[level] = {
              values: []
            }
          }

          let _v = {
            label: level1Item.label,
            value: level1Item.value,
          }

          // console.log('level1Index', level)

          if (this.data.childrenKey[level]) {
            // console.log('this.data.childrenKey', this.data.childrenKey)
            if (level1Item.hasOwnProperty(this.data.childrenKey[level])) {
              _v.children = level1Item[this.data.childrenKey[level]]
            }
           }

          inner_columns[level].values.push(_v)

          if (level1Item.value === model[level]) {
            selectedIndex = level1Index
          }
        })

        inner_value[level] = selectedIndex
        inner_columns[level].defaultIndex = selectedIndex
        if (Array.isArray(columns[selectedIndex].children) && columns[selectedIndex].children.length > 0) {
          self.buildSubOptions(columns[selectedIndex].children, model, level + 1, inner_value, inner_columns)
        }

        console.log('multipicker buildOptions', model, inner_value, inner_columns)
        return {
          inner_value,
          inner_columns
        }
      },
      buildSubOptions(columns, model, level, inner_value, inner_columns) {
        let selectedIndex = 0
        columns.forEach( (item, index) => {
          if (item.value === model[level]) {
            selectedIndex = index
          }
        })

        inner_value[level] = selectedIndex
        inner_columns[level] = {
          values: columns,
          defaultIndex: selectedIndex
        }

        if (Array.isArray(columns[selectedIndex].children) && columns[selectedIndex].children.length > 0) {
          this.buildSubOptions(columns[selectedIndex].children, model, level + 1, inner_value, inner_columns)
        }
      },
      onTrigger() {
        if (!this.data.disabled) {
          this.$native.emit('open-popup')
          setTimeout(() => {
            console.log('onTrigger showPopup')
            this.setData({
              showPopup: true
            })
          }, 0)
        }
      },
      onClickOverlay() {
        this.resetIndex()
        wx.nextTick(() => {
          this.$native.emit('close-popup')
          this.setData({
            showPopup: false
          })
        })
      },
      onCancel() {
        console.log(this.data.sModel)
        this.resetIndex()
        wx.nextTick(() => {
          this.$native.emit('close-popup')
          this.setData({
            showPopup: false
          })
        })
      },
      getLabel(inner_columns, newInnerValue) {
        let items = []

        inner_columns.forEach((columns, columnIndex) => {
          console.log('columns', columns)
          items.push(
            columns.values[ newInnerValue[columnIndex] ]
          )
        })

        console.log('items', items)

        return items.map(v => {
          if (v && v.label) {
            return v.label
          }
          return ''
        }).join()
      },
      setLabel(value){
        this.setData({
          labeltext: this.getLabel(value)
        })
      },
      initInner(model, cb = () => {}) {
        let inner_value = []
        this.getInnerValue(this.data.columns, model, inner_value)
        console.log('initInner inner_value', inner_value, this.data.inner_columns, model)
        this.setData({
          tmp_model: model,
          inner_value: inner_value
        }, cb)
      },
      renderLabel(model, cb = () => {}) {
        let inner_value = []
        this.getInnerValue(this.data.columns, model, inner_value)
        console.log('renderLabel inner_value', inner_value, this.data.inner_columns, model)
        let label = this.getLabel(this.data.inner_columns, inner_value)
        this.setData({
          tmp_model: model,
          labeltext: label,
          inner_value: inner_value
        }, cb)
      },
      getModelFrom(inner_columns, inner_value) {
        let ret = []
        inner_value.forEach((v, index) => {
          ret.push(
            inner_columns[index].values[v].value
          )
        })
        return ret
      },
      getModelFromIndexes(indexes) {
        let len = this.data.columns.length
        let tmp_model = []
        let cur = this.data.columns[indexes[0]]
        tmp_model.push(cur.value)
        for (let i = 1; i < len; i++) {
          cur = cur.children[indexes[i]]
          tmp_model.push(cur.value)
        }
        return tmp_model
      },
      onConfirm() {
        let picker = this.selectComponent('#picker')
        let values = picker.getValues()
        let lebeltext = values.map(v => v.value).join(',')
        let indexes = picker.getIndexes()
        this.$native.emit('close-popup')
        this.setData({
          labeltext: lebeltext,
          showPopup: false,
          inner_value: indexes
        })
        let tmp_model = this.getModelFromIndexes(indexes)
        console.log('indexes', indexes, tmp_model, this.getModelFromIndexes(indexes))

        this.callComponent(this.formItem, 'mtFormChange',  [this.data.tmp_model])
      },
      fireChange(newVal) {
        this.mtLiveCall(newVal)
        this.$native.emit('change', {
          value: newVal
        })
      },
      onChangeV2(e) {
        let self = this
        const { picker, value, index } = e.detail;
        console.log('picker', this.data.columns, picker.getValues(), value, index)
        if (index === 0) {
          let column1Index = this.data.columns.findIndex(v => v.value === value[0].value)
          console.log(column1Index)
          picker.setColumnValues(1, this.data.columns[column1Index].children);
          picker.setColumnIndex(1, 0)
          picker.setColumnValues(2, this.data.columns[column1Index].children[0].children);
          picker.setColumnIndex(2, 0)
        }
        if (index === 1) {
          let column1Index = this.data.columns.findIndex(v => v.value === value[0].value)
          let column2Index = this.data.columns[column1Index].children.findIndex(v => v.value === value[1].value)
          picker.setColumnValues(2, this.data.columns[column1Index].children[column2Index].children);
          picker.setColumnIndex(2, 0)
          console.log(column1Index, column2Index)
        }
        setTimeout(() => {
          self.setData({
            tmp_values: picker.getValues()
          })
        }, 30)
      },
      resetIndex() {
        let picker = this.selectComponent('#picker')
        console.log('resetIndex', this.data.inner_value, this.data.inner_columns, this.data.columns)
        if (picker) {
          let len = this.data.columns.length
          let indexes = []
          if (this.data.inner_value && this.data.inner_value.length === len) {
            indexes =  this.data.inner_value
          } else {
            indexes = Array(this.data.columns.length).fill(0)
          }
          let cur = this.data.columns
          for (let i = 0; i < len - 1; i++) {
            cur = cur[indexes[i]].children
            picker.setColumnValues(i + 1, cur);
          }
          // picker.setColumnValues(1, this.data.columns[column1Index].children);
          // picker.setColumnValues(2, this.data.columns[column1Index].children[column2Index].children);
          setTimeout(() => {
            picker.setIndexes(indexes)
            this.setData({
              activeSwiperIndex: 1
            })
          }, 300)
        }
      }
    },
  }
</script>

<style lang="less">
</style>
